/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package quanlinganhang.view;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.ListSelectionModel;
import javax.swing.table.TableColumnModel;
import org.jdesktop.swingx.JXTableHeader;
import org.jdesktop.swingx.decorator.ColorHighlighter;
import org.jdesktop.swingx.decorator.HighlightPredicate;
import org.jdesktop.swingx.decorator.HighlighterFactory;
import quanlinganhang.dao.AccountDAO;
import quanlinganhang.dao.LoginDAO;
import quanlinganhang.dto.AccountDTO;
import quanlinganhang.model.AccountTableModel;
import quanlinganhang.model.DepositTableModel;
import quanlinganhang.model.DrawMoneyTableModel;
import quanlinganhang.model.TransferTableModel;

/**
 *
 * @author SIPO
 */
public class AccountTransaction extends javax.swing.JPanel {

    private MyTableScroller ts = null;
    private AccountTableModel accModel = null;
    private DrawMoneyTableModel drawModel = null;
    private DepositTableModel depositModel = null;
    private TransferTableModel transModel = null;
    private String selectedAcc;         //current selected account

    /**
     * Creates new form AccountTransaction
     */
    public AccountTransaction() {
        try {
            accModel = new AccountTableModel();
        } catch (SQLException | ClassNotFoundException ex) {
            Logger.getLogger(ManageUser.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, "Có lỗi trong quá trình truy vấn "
                    + "dữ liệu", "Lỗi", JOptionPane.ERROR_MESSAGE);
        }
        initComponents();

        loadAccountTable();
    }

    /**
     * Load transfer information of selected account
     *
     * @param account
     */
    private void loadTransferTable(String account) {
        try {
            transModel = new TransferTableModel(account);
        } catch (SQLException ex) {
            Logger.getLogger(AccountTransaction.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, "Có lỗi trong quá trình truy vấn "
                    + "dữ liệu", "Lỗi", JOptionPane.ERROR_MESSAGE);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(AccountTransaction.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, "Có lỗi trong quá trình truy vấn "
                    + "dữ liệu", "Lỗi", JOptionPane.ERROR_MESSAGE);
        }
        jxTableTransaction.setModel(transModel);
        jxTableTransaction.setHighlighters(HighlighterFactory.createSimpleStriping());

        jxTableTransaction.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        //set màu sắc của row khi cuộn qua (màu background của row và màu text của row)
        jxTableTransaction.addHighlighter(new ColorHighlighter(HighlightPredicate.ROLLOVER_ROW,
                null, new Color(255, 102, 0)));

        TableColumnModel columnModel = jxTableTransaction.getColumnModel();
        jxTableTransaction.setTableHeader(new JXTableHeader(columnModel) {
            @Override
            public void updateUI() {
                super.updateUI();
                // need to do in updateUI to survive toggling of LAF 
                if (getDefaultRenderer() instanceof JLabel) {
                    ((JLabel) getDefaultRenderer()).setHorizontalAlignment(JLabel.CENTER);
                }
            }
        });
        jxTableTransaction.getColumn(0).setCellRenderer(new MyTableRenderer.IDRenderer());
        jxTableTransaction.getColumn(2).setCellRenderer(new MyTableRenderer.ColorRenderer());
    }

    /**
     * Load deposit money of selected account
     *
     * @param account
     */
    private void loadDepositTable(String account) {
        try {
            depositModel = new DepositTableModel(account);
        } catch (SQLException ex) {
            Logger.getLogger(AccountTransaction.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, "Có lỗi trong quá trình truy vấn "
                    + "dữ liệu", "Lỗi", JOptionPane.ERROR_MESSAGE);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(AccountTransaction.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, "Có lỗi trong quá trình truy vấn "
                    + "dữ liệu", "Lỗi", JOptionPane.ERROR_MESSAGE);
        }
        jxTableDeposit.setModel(depositModel);
        jxTableDeposit.setHighlighters(HighlighterFactory.createSimpleStriping());

        jxTableDeposit.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        //set màu sắc của row khi cuộn qua (màu background của row và màu text của row)
        jxTableDeposit.addHighlighter(new ColorHighlighter(HighlightPredicate.ROLLOVER_ROW,
                null, new Color(255, 102, 0)));

        TableColumnModel columnModel = jxTableDeposit.getColumnModel();
        jxTableDeposit.setTableHeader(new JXTableHeader(columnModel) {
            @Override
            public void updateUI() {
                super.updateUI();
                // need to do in updateUI to survive toggling of LAF 
                if (getDefaultRenderer() instanceof JLabel) {
                    ((JLabel) getDefaultRenderer()).setHorizontalAlignment(JLabel.CENTER);
                }
            }
        });
        jxTableDeposit.getColumn(0).setCellRenderer(new MyTableRenderer.IDRenderer());
        jxTableDeposit.getColumn(2).setCellRenderer(new MyTableRenderer.ColorRenderer());
    }

    /**
     * Load draw information of selected account
     *
     * @param account
     */
    private void loadDrawTable(String account) {
        try {
            drawModel = new DrawMoneyTableModel(account);
        } catch (SQLException ex) {
            Logger.getLogger(AccountTransaction.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, "Có lỗi trong quá trình truy vấn "
                    + "dữ liệu", "Lỗi", JOptionPane.ERROR_MESSAGE);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(AccountTransaction.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, "Có lỗi trong quá trình truy vấn "
                    + "dữ liệu", "Lỗi", JOptionPane.ERROR_MESSAGE);
        }
        jxTableWithDraw.setModel(drawModel);
        jxTableWithDraw.setHighlighters(HighlighterFactory.createSimpleStriping());

        jxTableWithDraw.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        //set màu sắc của row khi cuộn qua (màu background của row và màu text của row)
        jxTableWithDraw.addHighlighter(new ColorHighlighter(HighlightPredicate.ROLLOVER_ROW,
                null, new Color(255, 102, 0)));

        TableColumnModel columnModel = jxTableWithDraw.getColumnModel();
        jxTableWithDraw.setTableHeader(new JXTableHeader(columnModel) {
            @Override
            public void updateUI() {
                super.updateUI();
                // need to do in updateUI to survive toggling of LAF 
                if (getDefaultRenderer() instanceof JLabel) {
                    ((JLabel) getDefaultRenderer()).setHorizontalAlignment(JLabel.CENTER);
                }
            }
        });
        jxTableWithDraw.getColumn(0).setCellRenderer(new MyTableRenderer.IDRenderer());
        jxTableWithDraw.getColumn(2).setCellRenderer(new MyTableRenderer.ColorRenderer());
    }

    /**
     * Load list account
     */
    private void loadAccountTable() {
        //add pop up to table account
        JPopupMenu popup = new JPopupMenu();
        JMenuItem edit = new JMenuItem("Sửa");
        edit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                editAccount();
            }
        });
        JMenuItem delete = new JMenuItem("Xóa");
        delete.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteAccount();
            }
        });
        JMenuItem report = new JMenuItem("Báo cáo");
        JMenuItem reload = new JMenuItem("Tải lại");
        reload.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                reloadTable();
            }
        });
        popup.add(edit);
        popup.add(delete);
        //popup.add(report);
        popup.add(reload);
        jxTableAccount.setComponentPopupMenu(popup);

        jxTableAccount.setModel(accModel);
        jxTableAccount.setHighlighters(HighlighterFactory.createSimpleStriping());

        jxTableAccount.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        //set màu sắc của row khi cuộn qua (màu background của row và màu text của row)
        jxTableAccount.addHighlighter(new ColorHighlighter(HighlightPredicate.ROLLOVER_ROW,
                null, new Color(255, 102, 0)));

        TableColumnModel columnModel = jxTableAccount.getColumnModel();
        jxTableAccount.setTableHeader(new JXTableHeader(columnModel) {
            @Override
            public void updateUI() {
                super.updateUI();
                // need to do in updateUI to survive toggling of LAF 
                if (getDefaultRenderer() instanceof JLabel) {
                    ((JLabel) getDefaultRenderer()).setHorizontalAlignment(JLabel.CENTER);
                }
            }
        });
        jxTableAccount.getColumn(0).setCellRenderer(new MyTableRenderer.IDRenderer());
        jxTableAccount.getColumn(2).setCellRenderer(new MyTableRenderer.ColorRenderer());

        //get first account id
        selectedAcc = jxTableAccount.getValueAt(0, 1).toString();
        loadTransferTable(selectedAcc);
        loadDepositTable(selectedAcc);
        loadDrawTable(selectedAcc);
    }

    private void editAccount() {
        int currentRow = jxTableAccount.getSelectedRow();
        if (currentRow != - 1) {
            String acc = jxTableAccount.getValueAt(currentRow, 1).toString();
            try {
                AccountDTO account = AccountDAO.GetAccountFormId(acc);
                EditAccount editAcc = new EditAccount(LoginDAO.frmMain, true, account);
                editAcc.setVisible(true);
            } catch (SQLException | ClassNotFoundException | ParseException ex) {
                JOptionPane.showMessageDialog(null, "Có lỗi trong quá trình truy vấn "
                        + "dữ liệu", "Lỗi", JOptionPane.ERROR_MESSAGE);
                Logger.getLogger(AccountTransaction.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * Delete 1 account
     */
    private void deleteAccount() {
        int t = JOptionPane.showConfirmDialog(null, "Bạn có chắc chắn muốn xóa tài"
                + " khoản này", "Xác nhận", JOptionPane.YES_OPTION);
        if (t == JOptionPane.YES_OPTION) {
            int selectedRow = jxTableAccount.getSelectedRow();
            String currentAcc = jxTableAccount.getValueAt(selectedRow, 1).toString();
            try {
                AccountDAO.DeleteAccount(currentAcc);
                reloadTable();
                JOptionPane.showMessageDialog(jxTableAccount, "Xóa tài khoản thành "
                        + "công ", "Thành công", JOptionPane.OK_OPTION);

            } catch (ClassNotFoundException | SQLException ex) {
                Logger.getLogger(AccountTransaction.class.getName()).log(Level.SEVERE, null, ex);
                JOptionPane.showMessageDialog(null, "Có lỗi, không thể xóa tài khoản "
                        + "dữ liệu", "Lỗi", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    /**
     * Reload all table data
     */
    private void reloadTable() {
        try {
            accModel = new AccountTableModel();
        } catch (SQLException | ClassNotFoundException ex) {
            Logger.getLogger(AccountTransaction.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, "Có lỗi trong quá trình truy vấn "
                    + "dữ liệu", "Lỗi", JOptionPane.ERROR_MESSAGE);
        }
        loadAccountTable();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jxTableAccount = new org.jdesktop.swingx.JXTable();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jxTableWithDraw = new org.jdesktop.swingx.JXTable();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        jxTableTransaction = new org.jdesktop.swingx.JXTable();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jxTableDeposit = new org.jdesktop.swingx.JXTable();

        jxTableAccount.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jxTableAccount.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jxTableAccountMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jxTableAccount);

        jxTableWithDraw.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane3.setViewportView(jxTableWithDraw);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 885, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Rút tiền", jPanel2);

        jxTableTransaction.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane4.setViewportView(jxTableTransaction);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 885, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(15, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Chuyển khoản", jPanel3);

        jxTableDeposit.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(jxTableDeposit);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 885, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Gửi tiền", jPanel1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jTabbedPane1))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 233, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 263, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jxTableAccountMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jxTableAccountMouseClicked
        // TODO add your handling code here:
        int selectedRow = jxTableAccount.getSelectedRow();
        selectedAcc = jxTableAccount.getValueAt(selectedRow, 1).toString();
        loadTransferTable(selectedAcc);
        loadDepositTable(selectedAcc);
        loadDrawTable(selectedAcc);
    }//GEN-LAST:event_jxTableAccountMouseClicked
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTabbedPane jTabbedPane1;
    private org.jdesktop.swingx.JXTable jxTableAccount;
    private org.jdesktop.swingx.JXTable jxTableDeposit;
    private org.jdesktop.swingx.JXTable jxTableTransaction;
    private org.jdesktop.swingx.JXTable jxTableWithDraw;
    // End of variables declaration//GEN-END:variables
}
